<?php


	include("config.php");        
	ini_set('display_errors', 'On');
	include("classes/connect.php");
	include('classes/mylib.php');
	require_once('classes/class.jira.php');
	require_once('classes/class.phpmailer.php');
	require_once("classes/class.gmail.php");
	
	$gmail = new Gmail();
	
	$config->username= $jirauser;
	$config->password= $jirapass;
	$config->port= "";
	$config->host= $host;
	$jira = new Jira($config);
	
	$mailbx = $gmailserver.$boxname;
	$mbox = imap_open($mailbx,$gmailuser, $gmailpass, OP_READONLY) or die("can't connect: " . imap_last_error());
    
	$emails = imap_search($mbox,'SINCE '. date('d-M-Y',strtotime("-1 week")));// to search a sepecific time  'SINCE '. date('d-M-Y',strtotime("-1 week"))
	$count = 0;
	print "Count Mails: ".count($emails);
	print count($emails);
	if (count($emails)> 1) {
		rsort($emails);
		foreach($emails as $email_id){
			$overview = imap_fetch_overview($mbox,$email_id,0);
			//$ftypeArray = file_type($mbox,$overview[0]->msgno);
			
			//attachments handling
			
			/* get mail message */
			$message = imap_fetchbody($mbox,$email_id,2);
			
			/* get mail structure */
			$structure = imap_fetchstructure($mbox, $email_id);

			$attachments = array();
				/* if any attachments found... */
			if(isset($structure->parts) && count($structure->parts)) 
			{
				for($i = 0; $i < count($structure->parts); $i++) 
				{
					$attachments[$i] = array(
						'is_attachment' => false,
						'filename' => '',
						'name' => '',
						'attachment' => ''
					);
				
					if($structure->parts[$i]->ifdparameters) 
					{
						foreach($structure->parts[$i]->dparameters as $object) 
						{
							if(strtolower($object->attribute) == 'filename') 
							{
								$attachments[$i]['is_attachment'] = true;
								$attachments[$i]['filename'] = $object->value;
							}
						}
					}
				
					if($structure->parts[$i]->ifparameters) 
					{
						foreach($structure->parts[$i]->parameters as $object) 
						{
							if(strtolower($object->attribute) == 'name') 
							{
								$attachments[$i]['is_attachment'] = true;
								$attachments[$i]['name'] = $object->value;
							}
						}
					}
				
					if($attachments[$i]['is_attachment']) 
					{
						$attachments[$i]['attachment'] = imap_fetchbody($mbox, $email_id, $i+1);
						
						/* 4 = QUOTED-PRINTABLE encoding */
						if($structure->parts[$i]->encoding == 3) 
						{ 
							$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
						}
						/* 3 = BASE64 encoding */
						elseif($structure->parts[$i]->encoding == 4) 
						{ 
							$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
						}
					}
				}
			}
			
			$splitemail = explode("&lt;",$gmail->decode_imap_text($overview[0]->from));
			
			$email = str_replace("&gt;","",$splitemail[1]);
			$applicantName = $splitemail[0];
			$emailid = $gmail->decode_imap_text($overview[0]->message_id);
			$dateReceived = strtotime($gmail->decode_imap_text($overview[0]->date));
			$recordedDate = strtotime(date("Y-m-d H:i:s"));
			$subject=$gmail->decode_imap_text($overview[0]->subject);
			
			// print str_replace("&gt;","",$splitemail[1])."<br>";
			// print $splitemail[0]."<br>";
			// print $gmail->decode_imap_text($overview[0]->message_id)."<br>";
			// print $gmail->decode_imap_text($overview[0]->date)." - ".strtotime($gmail->decode_imap_text($overview[0]->date))."- ".date("Y-m-d H:i",$dateReceived)."<br>";
			// print "--------------------------------------------------------------------";
			
			$sqlq="select * from trn_emaildetails where emailid='".$emailid."' ";
			$rs =mysql_query($sqlq);
			if(mysql_num_rows($rs)!=1){
				//sending the applicant a mail
				
				// $a=str_replace("[name]",$applicantName,$mailrecieveddes);
				// $mail = new PHPMailer();
				// $body = $a;
				// $mail->AddReplyTo($AddReplyTo);
				// $mail->SetFrom($gmailuser);
				// $address = $email;
				// $mail->AddAddress($address, $fromname);
				// $mail->Subject    = $acknowledgement;
				// $mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
				// $mail->MsgHTML($body);
				// if(!$mail->Send()) {
				  // echo "Mailer Error: " . $mail->ErrorInfo;
				// } else {
				  // echo "Message sent!";
				// }
				
				//Creating JIRA Issue
				$count++;
				$data->fields->project->key=$project;
				$data->fields->summary=$applicantName;
				$data->fields->description="";
				$data->fields->issuetype->name='Task';
				
				$array=$jira->createIssue($data);
				$response = json_decode($array->responseBody);
				
				$query->id = $response->id;
                                 $types = explode("-", $response->id);
				
				$arrayother=$jira->queryIssue($query);
				$responseother=json_decode($arrayother->responseBody);
				
				$sqlquery = "INSERT INTO trn_emaildetails SET 
							email = '".$email."',
							emailid = '".$emailid."',
							applicantName = '".$applicantName."',
							dateReceived = '".$dateReceived."',
							recordedDate = '".$recordedDate."',
							currentAssignee = '".$responseother->issues[0]->fields->assignee->name."',
							subject = '".$subject."',
							vcode = UUID(),
							currentAssigneeName = '".$responseother->issues[0]->fields->assignee->displayName."',
							currentStatus = '".$responseother->issues[0]->fields->status->name."',
							currentSummary = '".$responseother->issues[0]->fields->summary."',
                            modifiedBy = '". $responseother->issues[0]->fields->reporter->displayName ."',
                            modifiedDate = '".  strtotime($responseother->issues[0]->fields->updated) ."',
							jiraTaskID = '".$response->id."'
							";
				mysql_query($sqlquery);
				
				$emailsarray.="Email received from ".$email." has been processed and created as a issue in JIRA.\r\n";
				
				$insertedID=mysql_insert_id();
				
				$activitysql="INSERT INTO trn_activity SET
								mainId = '".mysql_insert_id()."',
								status = '".$responseother->issues[0]->fields->status->name."',
								action = '".$action_one."',
								description = '".$action_one_des."',
								modifiedBy = '".$responseother->issues[0]->fields->assignee->name."',
								modifiedDate = '".$recordedDate."'				
							";
				mysql_query($activitysql);
				//saving attachments
				/* iterate through each attachment and save it */				
				
					foreach($attachments as $attachment)
					{
						if($attachment['is_attachment'] == 1)
						{
							$filename = $attachment['name'];
							if(empty($filename)) $filename = $attachment['filename'];
							
							if(empty($filename)) $filename = time() . ".dat";
							
							/* prefix the email number to the filename in case two emails
							 * have the attachment with the same file name.
							 */
							$filename1=str_replace(" ","",$filename);
							$fp = fopen("Attachments/".$insertedID. "-".$filename1, "w+");
							fwrite($fp, $attachment['attachment']);
							fclose($fp);
							
							$attachname=$insertedID."-".$filename1;
							$arrayother1=$jira->queryIssue($query);
							$responseother1=json_decode($arrayother1->responseBody);
							$currentdes=$responseother1->issues[0]->fields->description;
							$url="[http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['REQUEST_URI'])."/Attachments/".$attachname."]";
							$newdes=$currentdes.$url."\n";
							
							$data->fields->description=$newdes;
							$jira->updateIssue($data, $response->id);
							$sql="INSERT INTO trn_attachments SET
									id = '".$insertedID."',
									name = '".$attachname."'							
									";
							mysql_query($sql);
						}
					
					}
				$commentarray=$jira->queryIssue($query);
				$commentresponse=json_decode($commentarray->responseBody);
				$json->body=$commentresponse->issues[0]->fields->description."\n";
				$jira->addComment($query->id,$json);
				//Delete Message
				//imap_delete($mbox, $overview[0]->msgno);
				}
		} 
	}
	$emailsarray="\r\n".$emailsarray."\r\n\r\n";
	
	$log = new Logging();
	$log->lfile('log/cron_mail_log.txt');
	$log->lwrite($emailsarray);
	$log->lclose();
	
	
?>